
import Request from 'luch-request' // 使用npm 
import config from '../config.js'

let BASE_API = config.baseUrl  
const http = new Request({
	baseURL: BASE_API, //设置请求的base url
	timeout: 300000, //超时时长5分钟,
	header: {
		'Content-Type': 'application/json;charset=UTF-8;'
	}
})
//请求拦截器
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	const token = uni.getStorageSync('TOKEN'); 
	if (token) {
		config.header={
			"Authorization":'Bearer ' + token, 
		}
	} else{ 
		// uni.clearStorageSync();
		// uni.navigateTo({
		// 	url: "/pages/login/index"
		// }) 
	}
	// if (config.method === 'POST') { 
	// 	config.data = JSON.stringify(config.data); 
	// }
	// console.log(config.data);
	return config
}, error => { 
	return Promise.resolve(error)
})
// 响应拦截器
http.interceptors.response.use((response) => {
	// console.log(response.data)  
	if (response.data.code == 401) { 
		uni.clearStorageSync();
		uni.navigateTo({
			url: "/pages/login/index"
		})
	}
	return response.data
}, (error) => {
	//未登录时清空缓存跳转
	console.log(error);
	// if (error.statusCode == 401) {
	// 	uni.clearStorageSync();
	// 	uni.switchTab({
	// 		url: "/pages/login/index"
	// 	})
	// }
	return Promise.resolve(error)
})
// 不带token请求
const httpRequest = new Request({
	baseURL: BASE_API, //设置请求的base url
	timeout: 300000, //超时时长5分钟,
	header: { 
		'Content-Type': 'application/json;charset=UTF-8;'
	}
})
//请求拦截器
httpRequest.interceptors.request.use((config) => {  
	const token = uni.getStorageSync('TOKEN');
	if (token) {
		config.header={ 
			"Authorization":'Bearer ' + token, 
		}
	} 
	return config
}, error => {
	return Promise.resolve(error)
})
// 响应拦截器
httpRequest.interceptors.response.use((response) => {  
	return response.data
}, (error) => { 
	return Promise.resolve(error)
}) 
export default {
	http,
	httpRequest,
	BASE_API
};